package com.webex.ta.hydra.gui.wm;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-10-21
 * Time: 13:19:45
 */
public class FocusWatcher implements ContainerListener, FocusListener {
    private Component topComponent;

    public FocusWatcher(Component c) {
        install(c);
    }

    public final void install(Component c) {
        topComponent = c;
        _install(c);
    }

    private void _install(Component c) {
        if ( c instanceof Container) {
            Container container = (Container) c;
            int cnt = container.getComponentCount();
            for (int i = 0; i < cnt; i++)
                _install(container.getComponent(i));
            container.addContainerListener(this);
        }
        if (c instanceof JMenuItem || c instanceof JMenuBar)
            return;
        c.addFocusListener(this);
    }

    public void componentAdded(ContainerEvent e) {
        _install(e.getChild());
    }

    public void componentRemoved(ContainerEvent e) {

    }

    public void focusGained(FocusEvent e) {
        Component c = e.getComponent();
        if (e.isTemporary() || !c.isShowing())
            return;

        setFocusedComponent(c);
    }

    public void focusLost(FocusEvent e) {
        Component c = e.getOppositeComponent();
        if (c!= null && !SwingUtilities.isDescendingFrom(c, topComponent))
            focusLostImpl(e);
    }

    public void setFocusedComponent(Component c) {
        if (!isFocusedComponentChangeValid(c))
            return;

        focusedComponentChanged(c);
    }

    protected void focusedComponentChanged(Component component) { }

    protected void focusLostImpl(final FocusEvent e) { }

    protected boolean isFocusedComponentChangeValid(Component c) {
        return c != null;
    }
}
